package org.example.demo;

import org.objectweb.asm.ClassWriter;
import org.objectweb.asm.MethodVisitor;
import org.objectweb.asm.Opcodes;

public class HelloWordAsm implements Opcodes {
    public static byte[] genHelloWorldClass(){
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES);
        cw.visit(V1_8,ACC_PUBLIC|ACC_SUPER,"demo/HelloWorldAsm",
                null,
                "java/lang/Object",
                null);

        {
            // 添加无参构造方法
            MethodVisitor mv1 = cw.visitMethod(
                    ACC_PUBLIC,
                    "<init>",
                    "()V",
                    null,
                    null
            );
            mv1.visitCode();
            mv1.visitVarInsn(ALOAD,0);
            // 调用父类的构造方法
            mv1.visitMethodInsn(
                    INVOKESPECIAL,
                    "java/lang/Object",
                    "<init>",
                    "()V",
                    false
            );
            mv1.visitInsn(RETURN);
            mv1.visitMaxs(1,1);
            mv1.visitEnd();
        }

        {
            // 添加一个toString 方法，返回String
            MethodVisitor mv2 = cw.visitMethod(
                    ACC_PUBLIC,
                    "toString",
                    "()Ljava/lang/String;",
                    null,
                    null
            );

            mv2.visitCode();
            mv2.visitLdcInsn("this is a HelloAsm class obj");
            mv2.visitInsn(ARETURN);
            mv2.visitMaxs(1,1);
            mv2.visitEnd();
        }
        cw.visitEnd();

        return cw.toByteArray();
    }
}
